package com.x.service;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.smart.exception.BizException;
import com.x.dao.UserDao;
import com.x.model.LoginInfo;
import com.x.model.RegisterInfo;
import com.x.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Value("${smart.tokenx.key}")
    private String tokenKey;
    @Autowired
    private UserDao userDao;
    public String register(RegisterInfo registerInfo) {
        //省略校验
        User user = userDao.select(registerInfo.getTel());
        if(ObjUtil.isNotEmpty(user)){
            throw new BizException(405,"手机号已存在");
        }

        int rowNum = userDao.insert(registerInfo);

        if(rowNum != 1){
            throw new BizException(406,"注册失败");
        }

        return "ok";
    }

    public String login(LoginInfo loginInfo) {

        //省略校验
        User user = userDao.login(loginInfo.getTel(),loginInfo.getPassword());
        if(ObjUtil.isEmpty(user)){
            throw new BizException(406,"手机号或密码不正确");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("tel", user.getTel().substring(0, 4) + "****" + user.getTel().substring(8));
        map.put("nickName", user.getNickName());
        map.put("role", "admin");
        map.put(JWT.EXPIRES_AT, System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000);
        String token = JWTUtil.createToken(map, tokenKey.getBytes());
        return token;
    }
}
